package models.msgtemp.merchant;

import address.Address;
import enums.OrderStatus;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import models.helper.WxMpHelper;
import models.merchant.Merchant;
import models.merchant.enums.VerifyState;
import models.weixin.WebUser;
import order.Order;
import order.OrderItem;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import util.common.ConvertUtil;
import utils.DateUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/16.
 */
public class WxMpMerchantMsgTemp {

    /**
     * 通知用户商户是否通过审核
     * @param merchant
     * @return
     */
    public static Boolean sendMsgforAuditMerchant(Merchant merchant ){
        Boolean sendSuccess = false ;

        //判断商户用户是否存在
        if(merchant == null || merchant.webUserId ==null ){
            Logger.info("------------------商户用户不存在,无法发送模板消息!");

            sendSuccess = false;
            return  sendSuccess ;

        }
        String auditResult = merchant.verifyState == VerifyState.PASS ? "审核通过" : "审核不通过" ;
        //判断用户openId是否存在
        WebUser webUser = WebUser.findByUserId(merchant.webUserId);
        if(webUser == null || webUser.openId == null){
            Logger.info("------------------用户openID不存在,无法发送模板消息!");

            sendSuccess = false;
            return  sendSuccess ;
        }
        String openId = webUser.openId;
        WxMpService wxMpService = WxMpHelper.getWxMpService();

        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("-NyepQmqGd2akUbzeXHXo-HHOpXpRSrnHFdZJVbpc9s")
                .build();
//        wxMpTemplateMessage.setTemplateId("-NyepQmqGd2akUbzeXHXo-HHOpXpRSrnHFdZJVbpc9s");
        String weixinUrl = Play.configuration.getProperty("weixin.merchant.url");
        wxMpTemplateMessage.setUrl(weixinUrl);
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！您新建的商户"+auditResult+"！" ));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1",merchant.name));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2",auditResult));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", DateUtil.dateToString(new Date() , "yyyy-MM-dd")));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "内容修改：如有疑问欢迎拨打热线15263399860"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            sendSuccess = true;
        } catch (WxErrorException e) {
            Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
        }
        return sendSuccess;
    }

    /**
     * 支付成功后，商户推送信息
     * @param order
     * @return
     */
    public static Boolean sendMsgforPaySuccessMerchant(Order order){
        Boolean sendSuccess = false ;
        Logger.info("------------订单支付成功,开始发送消息至商户");
        if(order == null ){
            Logger.info("-------------订单信息不存在,发送失败!");
             sendSuccess = false ;
            return sendSuccess;
        }
        List<Map<String , Object> > merchantlist = OrderItem.getListForWeiXinMsgByOrderId(order);
        if(merchantlist == null || merchantlist.size() == 0){
            Logger.info("-------------未获取到商户信息,发送失败!");
             sendSuccess = false ;
            return sendSuccess;
        }
        if(order.webUser == null){
            Logger.info("-------------未获取到订单客户信息,发送失败!");
             sendSuccess = false ;
            return sendSuccess;
        }
        Address address = Address.findDefaultAddressByUser(order.webUser.id);
        if(address == null){
            Logger.info("-------------客户地址获取失败!");
             sendSuccess = false ;
            return sendSuccess;
        }

        for(Map<String , Object> map : merchantlist){
            WebUser webUser = WebUser.findByUserId(ConvertUtil.toLong(map.get("web_user_id")));
            if(webUser == null || webUser.openId == null){
                continue;
            }
            String openId = webUser.openId;
            WxMpService wxMpService = WxMpHelper.getWxMpService();

            WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                    .toUser(openId)
                    .templateId("i9pVgBM_WdDIdsw2JbasaYXHLz8ooFZmLhZCxr65HyA")
                    .build();
//        wxMpTemplateMessage.setTemplateId("-NyepQmqGd2akUbzeXHXo-HHOpXpRSrnHFdZJVbpc9s");
            String weixinUrl = Play.configuration.getProperty("weixin.merchant.url");
            wxMpTemplateMessage.setUrl(weixinUrl);
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！您有新订单!"));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1", ""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2", util.common.DateUtil.dateToString(order.createdAt,"yyyy-MM-dd HH:mm:ss")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", address !=null ? address.communityName+address.address :""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword4", address != null ? address.phone : ""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword5", OrderStatus.getOrderStatus(order.status)));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "点击查看!"));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                sendSuccess = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }

        }
        return sendSuccess;

    }

    /**
     * 获取验证码,用于修改密码
     *
     * @param merchant
     * @return
     */
    public static Boolean sendVerificationCodeToTheUser(Merchant merchant) {
        Logger.info("LOGGER -sendVerificationCodeToTheUser 20171130000000001-----------------用户忘记密码 发送验证码给用户!");

        Boolean isSuccess = false;
        if (merchant == null) {
            Logger.info("------------------商户信息不存在,无法发送模板消息!");
            isSuccess = false;
            return isSuccess;
        }
        WebUser webUser = WebUser.findByUserId(merchant.webUserId);
        if (webUser == null || StringUtils.isBlank(webUser.openId)) {
            Logger.info("------------------商户微信用户信息不存在,无法发送模板消息!");

            isSuccess = false;
            return isSuccess;
        }
        String openId = webUser.openId;
        WxMpService wxMpService = WxMpHelper.getWxMpService();

        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("-NyepQmqGd2akUbzeXHXo-HHOpXpRSrnHFdZJVbpc9s")
                .build();

        String weixinUrl = Play.configuration.getProperty("merchant.base.url") + "/login/verificationCodeLogin";
        Logger.info("WeixinUrl : %s" + weixinUrl);
        wxMpTemplateMessage.setUrl(weixinUrl);
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！验证码为:" + merchant.verificationCode + ",有效时间为5分钟,请在5分钟内完成登录并修改密码!"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1", merchant.loginName));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2", ""));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", "修改登录密码"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword4", merchant.verificationCode));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword5", "5分钟"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "请确保是本人操作,如果不是,请忽略.点击进入验证码登录页面."));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            isSuccess = true;
        } catch (WxErrorException e) {
            Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", webUser.openId, e.getMessage());
        }


        return isSuccess;
    }

    /**
     * 订单已送达,消息推送至客户,提醒客户收取商品
     *
     * @param order
     * @param order
     * @return
     */
    public static Boolean sendMsgForOrderArrive(Order order) {
        Logger.info("LOGGER -sendMsgForOrderArrive 20171130000000001-----------------订单已配送至站点,提醒用户自取商品!");

        Boolean isSuccess = false;
        if (order == null) {
            Logger.info("------------------订单信息不存在,无法发送模板消息!");
            isSuccess = false;
            return isSuccess;
        }
        WebUser webUser = order.webUser;
        if (webUser == null || StringUtils.isBlank(webUser.openId)) {
            Logger.info("------------------商户微信用户信息不存在,无法发送模板消息!");

            isSuccess = false;
            return isSuccess;
        }
        String openId = webUser.openId;

//        WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
        WxMpService wxMpService = WxMpHelper.getWxMpService();

        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("VRWsRMqJSh8S7mMyQNeSAQmzgsix6W9879U3EY9RNjI")
                .build();

 //       wxMpTemplateMessage.setTemplateId("VRWsRMqJSh8S7mMyQNeSAQmzgsix6W9879U3EY9RNjI");
        String weixinUrl = Play.configuration.getProperty("weixin.merchant.url");
        wxMpTemplateMessage.setUrl(weixinUrl);
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！您的订单已到达校园快递中心!"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1", order.orderNumber));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2", "日照职业技术学院德润楼126"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", "早上9:30点到晚上5:30"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword4", "校园快递"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword5", "15263399860"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "如有疑问欢迎拨打热线15263399860"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            isSuccess = true;
        } catch (WxErrorException e) {
            Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
        }
        return isSuccess;
    }

//        public static void sendTempTest(Merchant merchant) {
//        WebUser webUser = WebUser.findById(merchant.webUserId);
//        WxMpService wxMpService = WxMpHelper.getWxMpService();
//        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
//                .toUser(webUser.openId)
//                .templateId("gxxid-84bNfJGZRYCEvKERu1fu-ZYolxJYM46qyF300")
//                .build();
//        templateMessage.getData().add(new WxMpTemplateData("first", "商户端发送模板消息测试", "#dbdbdb"));
//        templateMessage.getData().add(new WxMpTemplateData("keyword1", "当前系统", "#dbdbdb"));
//        templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtil.dateToString(new Date() , "yyyy-MM-dd HH:mm:ss"), "#dbdbdb"));
//        templateMessage.getData().add(new WxMpTemplateData("remark", "商户端测试成功", "#dbdbdb"));
//        try {
//            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
//        } catch (WxErrorException e) {
//            Logger.info("模板消息发送失败： %s" , e.getMessage());
//            e.printStackTrace();
//        }
//    }





    /**
     * 开始配送通知
     * @param order
     * @return
     */
    public static Boolean sendMsgForOrderDistribute(Order order ){
        Boolean isSuccess = false;
        if (order == null) {
            Logger.info("------------------订单信息不存在,无法发送模板消息!");
            isSuccess = false;
            return isSuccess;
        }
        WebUser webUser = order.webUser;
        if (webUser == null || StringUtils.isBlank(webUser.openId)) {
            Logger.info("------------------商户微信用户信息不存在,无法发送模板消息!");

            isSuccess = false;
            return isSuccess;
        }

        String openId = webUser.openId;
        WxMpService wxMpService = WxMpHelper.getWxMpService();
        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("vWLnDSlLMzggHbR47EM1HEVWcR2_MXyvDOIM8EiJ9ts")
                .build();
        String weixinUrl = Play.configuration.getProperty("weixin.merchant.url");
        wxMpTemplateMessage.setUrl(weixinUrl);
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "感谢您在卓创商城上购物。您购买的商品，商家已发货，请耐心等待。"));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1", order.orderNumber));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtil.dateToString(order.createdAt,"yyyy-MM-dd HH:mm:ss")));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", order.amount.toString()));
        wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "卓创商城：http://rizhiweixin.ulmsale.net/"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            isSuccess = true;
        } catch (WxErrorException e) {
            Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            isSuccess = false;
        }
        return isSuccess;

    }

}
